package org.springframework.beans.factory.support;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import java.lang.reflect.Constructor;
/**
 * @author derekyi
 * @date 2020/11/23
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy {

	/**
	 * 简单的bean构造方法实例化策略，根据bean的无参构造函数实例化对象
	 *
	 * @param beanDefinition
	 * @return
	 * @throws BeansException
	 */

	//JDK实例化是通过反射实现的
	@Override
	public Object instantiate(BeanDefinition beanDefinition) throws BeansException {
		//这个方法里是用构造方法生成bean，这里是空参构造，具体数据的存入后面会涉及
		Class beanClass = beanDefinition.getBeanClass();
		try {
			//beanDefinition对象里有bean的类字节码对象，里面可以得到构造方法
			Constructor constructor = beanClass.getDeclaredConstructor();
			return constructor.newInstance();//用构造方法得到实例
		} catch (Exception e) {
			throw new BeansException("Failed to instantiate [" + beanClass.getName() + "]", e);
		}
	}
}
